package com.wish.wishsystem_management.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wish.wishsystem_management.config.EsUtils;
import com.wish.wishsystem_management.entity.ESSaveRoomParam;
import com.wish.wishsystem_management.entity.TbRoomInfo;
import com.wish.wishsystem_management.mapper.TbRoomInfoMapper;
import com.wish.wishsystem_management.service.IEsSyncTimeService;
import com.wish.wishsystem_management.service.ITbRoomInfoService;
import dto.systemDto.IdNamePair;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;
import vo.QueryRoomInfoResponseVo;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhaiwj
 * @since 2021-03-22
 */
@Service
@Slf4j
public class TbRoomInfoServiceImpl extends ServiceImpl<TbRoomInfoMapper, TbRoomInfo> implements ITbRoomInfoService {

    @Autowired
    private IEsSyncTimeService iEsSyncTimeService;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;


    @Override
    public void updateRoomInfoAllEs() {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date newDate = new Date();
        log.info("-----start  RoomInfoServiceImpl  updateRoomInfoAllEs ... -----------{}", format.format(newDate));
        HashMap<String, Object> map = new HashMap<>();
        //把es_sync_time时间都进行更新
        map.put("newDate", format.format(newDate));
        this.iEsSyncTimeService.updateEsSyncTimeAll(map);
        //查询条数
        int roomInfoTotal = this.queryRoomInfoTotal();
        Integer pageSize = 500;
        //如果总条数超过每页条数，当前页：roomInfoTotal / pageSize
        //如果总条数小于每页条数，当前页：(roomInfoTotal / pageSize)+1
        Integer pageNum = roomInfoTotal / pageSize != 0 ? (roomInfoTotal / pageSize) + 1 : (roomInfoTotal / pageSize);
        //分页循环取数据
        for (int j = 0; j < pageNum; j++) {
            map.clear();
            map.put("pageSize", pageSize);
            map.put("pageNum", j * pageSize);

            //获取所有的房源信息
            List<QueryRoomInfoResponseVo> queryRoomInfoList = new ArrayList<>();
            queryRoomInfoList = this.queryAllList(map);

            String ids = "";
            List<ESSaveRoomParam> param = new ArrayList<>();

            //判断房源状态，只有为待租中才同步es及未删除状态
            for (int i = queryRoomInfoList.size() - 1; i >= 0; i--) {
                if (queryRoomInfoList.get(i).getStatus() != 0 || queryRoomInfoList.get(i).getDelFlg() == 1 || queryRoomInfoList.get(i).getPublishStatus() == 0 || queryRoomInfoList.get(i).getHStatus() == 1) {
                    ids += "," + queryRoomInfoList.get(i).getRoomId();
                    queryRoomInfoList.remove(i);
                } else {
                    ESSaveRoomParam esSaveRoomParam = new ESSaveRoomParam();
                    BeanUtils.copyProperties(queryRoomInfoList.get(i), esSaveRoomParam);
                    //把没问题的数据存入集合
                    param.add(esSaveRoomParam);
                }
            }

            //List<String> idsList = new ArrayList<>();
            if (!StringUtils.isEmpty(ids)) {
                //idsList = Arrays.asList(ids.substring(1).split(","));
                try {
                    EsUtils.delete(elasticsearchTemplate, String.class, new String[]{ids});
                    Date date = new Date();
                    log.info("------ RoomInfoServiceImpl ---> updateRoomInfoAllEs 中 deleteBulk  成功-------{},共{}条", format.format(date), ids.length());
                } catch (Exception e) {
                    e.printStackTrace();
                    Date date = new Date();
                    log.info("------ RoomInfoServiceImpl ---> updateRoomInfoAllEs  中 deleteBulk  异常-------{},共{}条", format.format(date), ids.length());
                }
            }
            //向es中添加数据

            try {
                //2.构建批量插入
//                List<IndexQuery> queries = new ArrayList<>();
//                //上面的那几步也可以使用IndexQueryBuilder来构建
                for (ESSaveRoomParam roomParam : param) {
                    EsUtils.save(elasticsearchTemplate, roomParam, roomParam.getRoomId());
                }
                /*//4.添加数据
                elasticsearchTemplate.bulkIndex(queries);*/
                Date date = new Date();
                log.info("------ RoomInfoServiceImpl ---> updateRoomInfoAllEs 中 deleteBulk  成功-------{},共{}条", format.format(date), ids.length());
            } catch (Exception e) {
                e.printStackTrace();
                Date date = new Date();
                log.info("------ RoomInfoServiceImpl ---> updateRoomInfoAllEs  中 deleteBulk  异常-------{},共{}条", format.format(date), ids.length());
            }
        }
    }

    /**
     * 总条数
     *
     * @return
     */
    @Override
    public int queryRoomInfoTotal() {
        return baseMapper.queryRoomInfoTotal();
    }

    /**
     * es全量  ：查询房源列表 and 房产信息 and 楼盘信息
     */
    @Override
    public List<QueryRoomInfoResponseVo> queryAllList(HashMap<String, Object> map) {

        List<QueryRoomInfoResponseVo> queryRoomInfoList = this.baseMapper.queryRoomInfoList(map);

        //循环将发生变化的值放到List<ESSaveRoomParam>中
        for (QueryRoomInfoResponseVo queryRoomInfoResponseVo : queryRoomInfoList) {
            //取出地铁id进行判断循环
            String subway = queryRoomInfoResponseVo.getSubway();
            if (subway != null && StringUtils.isNotBlank(subway)) {
                List<IdNamePair<Integer, String>> subwayList = new ArrayList<>();
                String[] split = subway.split(",");
                for (String string : split) {
                    IdNamePair<Integer, String> subwayIdName = this.baseMapper.getSubWayByIdList(Integer.parseInt(string));
                    //查询到的地铁名字添加到集合中
                    subwayList.add(subwayIdName);
                }
                queryRoomInfoResponseVo.setSubwayList(subwayList);
            }
            //取出商圈id进行判断循环
            String businessCircleSplit = queryRoomInfoResponseVo.getBusinessCircle();
            if (businessCircleSplit != null && StringUtils.isNotBlank(businessCircleSplit)) {
                List<IdNamePair<Integer, String>> businessCircleList = new ArrayList<>();
                String[] split = businessCircleSplit.split(",");
                for (String businessCircle : split) {
                    IdNamePair<Integer, String> businessCircleIdName = this.baseMapper.getBusinessCircleByIdList(businessCircle);
                    //查询到的商圈名字添加到集合中
                    businessCircleList.add(businessCircleIdName);
                }
                queryRoomInfoResponseVo.setBusinessCircleList(businessCircleList);
            }
        }


        return queryRoomInfoList;
    }

    /**
     * es全量  ：查询房源列表 and 房产信息 and 楼盘信息
     */
    @Override
    public List<QueryRoomInfoResponseVo> queryRoomInfoList(HashMap<String, Object> map) {
        Integer object = (Integer) map.get("status");
        List<QueryRoomInfoResponseVo> queryRoomInfoList = null;
        if (object == 1) {
            queryRoomInfoList = this.baseMapper.queryRoomInfoList(map);
        } else if (object == 2) {
            queryRoomInfoList = this.baseMapper.queryHouseInfoList(map);
        } else if (object == 3) {
            queryRoomInfoList = this.baseMapper.queryPremisesInfoList(map);
        }

        //判断有没有变化的数据
        if (queryRoomInfoList == null) {
            return null;
        }

        //循环将发生变化的值放到List<ESSaveRoomParam>中
        for (QueryRoomInfoResponseVo queryRoomInfoResponseVo : queryRoomInfoList) {
            //取出地铁id进行判断循环
            String subway = queryRoomInfoResponseVo.getSubway();
            if (subway != null && StringUtils.isNotBlank(subway)) {
                List<IdNamePair<Integer, String>> subwayList = new ArrayList<>();
                String[] split = subway.split(",");
                for (String string : split) {
                    IdNamePair<Integer, String> subwayIdName = this.baseMapper.getSubWayByIdList(Integer.parseInt(string));
                    subwayList.add(subwayIdName);
                }
                queryRoomInfoResponseVo.setSubwayList(subwayList);
            }
            //取出商圈id进行判断循环
            String businessCircleSplit = queryRoomInfoResponseVo.getBusinessCircle();
            if (businessCircleSplit != null && StringUtils.isNotBlank(businessCircleSplit)) {
                List<IdNamePair<Integer, String>> businessCircleList = new ArrayList<>();
                String[] split = businessCircleSplit.split(",");
                for (String businessCircle : split) {
                    IdNamePair<Integer, String> subwayIdName = this.baseMapper.getBusinessCircleByIdList(businessCircle);
                    businessCircleList.add(subwayIdName);
                }
                queryRoomInfoResponseVo.setBusinessCircleList(businessCircleList);
            }

        }

        return queryRoomInfoList;
    }


}
